import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/enums/get_sms_code_click_type.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/login/model/verification_code_resp.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/toast_utils.dart';

/// 忘记密码 页面
class ForgotPasswordPage extends ConsumerStatefulWidget {
  const ForgotPasswordPage({super.key});

  @override
  ConsumerState<ForgotPasswordPage> createState() => _ForgotPasswordPageState();
}

class _ForgotPasswordPageState extends ConsumerState<ForgotPasswordPage> {
  final _formKey = GlobalKey<FormState>();
  final _phoneController = TextEditingController();
  final _codeController = TextEditingController();
  final textColor = Colors.black;
  Timer? _countdownTimer;
  final _countdownTimeInit = 60;
  var _uuid = '';

  int countdownTime = 0;
  GetSmsCodeClickType clickButtonType = GetSmsCodeClickType.getCode;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback(_afterLayout);
    super.initState();
  }

  // Widget绘制完成后的回调
  void _afterLayout(Duration timeStamp) {
    setState(() {
      countdownTime = 0;
    });
  }

  /// 获取验证码
  _fetchCode() async {
    ToastUtils.showLoading();
    var res = await post<VerificationCodeResp, VerificationCodeResp>('/app/user/getSmsCode',
        data: {'phone': _phoneController.text}, decodeType: VerificationCodeResp());
    res.when(success: (resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        ToastUtils.showSuccess('验证码已发送');
        // _uuid = resp.data!.uuid!;
        // 开始倒计时60秒
        countdownTime = _countdownTimeInit;
        _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
          countdownTime = _countdownTimeInit - timer.tick;
          if (timer.tick >= _countdownTimeInit) {
            timer.cancel();
            clickButtonType = GetSmsCodeClickType.getCode;
          }
          setState(() {});
        });
      }
    }, failure: (String msg, int code) {
      XLogger.error('获取验证码失败 code: $code msg: $msg');
    });
  }

  /// 验证手机号
  _verifyPhone() async {
    final postData = {
      'phone': _phoneController.text,
      'code': _codeController.text,
      'uuid': _uuid,
    };
    ToastUtils.showLoading();
    var res = await post<VerificationCodeResp, VerificationCodeResp>('/app/user/smsCodeVerify',
        data: postData, decodeType: VerificationCodeResp());
    res.when(success: (resp) {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        // 校验验证码成功，跳转到重置密码页面
        // context.pushNamed('reset-password', queryParameters: {'uuid': resp.data!.uuid, 'phone': _phoneController.text});
      } else {
        ToastUtils.showToast(resp.msg ?? '验证码错误');
      }
    }, failure: (String msg, int code) {
      XLogger.error('校验验证码失败 code: $code msg: $msg');
    });
  }

  @override
  void dispose() {
    _countdownTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios_new, color: AppTheme.themeConfig.primaryTextColor),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            // 标题区域
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 20),
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [
                    AppTheme.themeConfig.primaryColor.withOpacity(0.08),
                    AppTheme.themeConfig.primaryColor.withOpacity(0.03),
                  ],
                ),
                borderRadius: BorderRadius.circular(20),
                border: Border.all(
                  color: AppTheme.themeConfig.primaryColor.withOpacity(0.2),
                  width: 1,
                ),
              ),
              child: Row(
                children: [
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [
                          AppTheme.themeConfig.primaryColor.withOpacity(0.15),
                          AppTheme.themeConfig.primaryColor.withOpacity(0.05),
                        ],
                      ),
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      Icons.lock_reset,
                      color: AppTheme.themeConfig.primaryColor,
                      size: 28,
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '忘记密码',
                          style: TextStyle(
                            fontSize: 24,
                            fontWeight: FontWeight.w700,
                            color: AppTheme.themeConfig.primaryTextColor,
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          '请输入手机号获取验证码',
                          style: TextStyle(
                            fontSize: 14,
                            color: AppTheme.themeConfig.secondaryTextColor,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 40),
            // 表单
            Container(
              margin: const EdgeInsets.only(left: 20, right: 20),
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    // 手机号码
                    TextFormField(
                      controller: _phoneController,
                      style: TextStyle(color: textColor),
                      decoration: InputDecoration(
                        hintText: "请输入手机号码",
                        hintStyle: TextStyle(
                          fontSize: 15,
                          color: AppTheme.themeConfig.infoTextColor,
                        ),
                        prefixIcon: Icon(
                          Icons.phone_android,
                          color: AppTheme.themeConfig.primaryColor,
                        ),
                        contentPadding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 18.0),
                        filled: true,
                        fillColor: AppTheme.themeConfig.greyBgColor,
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(16),
                          borderSide: BorderSide(
                            color: AppTheme.themeConfig.dividerColor,
                            width: 1.5,
                          ),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(16),
                          borderSide: BorderSide(
                            color: AppTheme.themeConfig.dividerColor,
                            width: 1.5,
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(16),
                          borderSide: BorderSide(
                            color: AppTheme.themeConfig.primaryColor,
                            width: 2,
                          ),
                        ),
                      ),
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return '请输入手机号码';
                        }
                        // 手机号正则校验
                        RegExp exp = RegExp(r"^1[3456789]\d{9}$");
                        if (!exp.hasMatch(value)) {
                          return '请输入正确的手机号码';
                        }
                        return null;
                      },
                      inputFormatters: [
                        // 只允许输入数字
                        FilteringTextInputFormatter.allow(RegExp('[0-9]')),
                        // 限制输入为11个数字
                        LengthLimitingTextInputFormatter(11),
                      ],
                      // 数字键盘
                      keyboardType: TextInputType.number,
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    Stack(
                      children: [
                        TextFormField(
                          controller: _codeController,
                          style: TextStyle(color: textColor),
                          decoration: InputDecoration(
                            hintText: "请输入验证码",
                            hintStyle: TextStyle(
                              fontSize: 15,
                              color: AppTheme.themeConfig.infoTextColor,
                            ),
                            prefixIcon: Icon(
                              Icons.verified_user,
                              color: AppTheme.themeConfig.primaryColor,
                            ),
                            contentPadding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 18.0),
                            filled: true,
                            fillColor: AppTheme.themeConfig.greyBgColor,
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(16),
                              borderSide: BorderSide(
                                color: AppTheme.themeConfig.dividerColor,
                                width: 1.5,
                              ),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(16),
                              borderSide: BorderSide(
                                color: AppTheme.themeConfig.dividerColor,
                                width: 1.5,
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(16),
                              borderSide: BorderSide(
                                color: AppTheme.themeConfig.primaryColor,
                                width: 2,
                              ),
                            ),
                          ),
                          validator: (value) {
                            // 点击验证码按钮时，不校验
                            if (clickButtonType == GetSmsCodeClickType.getCode) {
                              return null;
                            }
                            if (value == null || value.isEmpty) {
                              return '请输入验证码';
                            }
                            return null;
                          },
                          inputFormatters: [
                            // 只允许输入数字
                            FilteringTextInputFormatter.allow(RegExp('[0-9]')),
                            // 限制输入为6个数字
                            LengthLimitingTextInputFormatter(6),
                          ],
                          // 数字键盘
                          keyboardType: TextInputType.number,
                        ),
                        // 获取验证码
                        Positioned(
                          right: 0,
                          child: GestureDetector(
                            onTap: () {
                              // 倒计时未结束时，不允许点击
                              if (countdownTime > 0) {
                                return;
                              }
                              // 校验手机号码
                              setState(() {
                                clickButtonType = GetSmsCodeClickType.getCode;
                              });
                              if (_formKey.currentState!.validate()) {
                                // 获取验证码
                                _fetchCode();
                              }
                            },
                            child: Container(
                              alignment: Alignment.center,
                              width: 120,
                              height: 56,
                              decoration: BoxDecoration(
                                gradient: countdownTime > 0
                                    ? null
                                    : LinearGradient(
                                        colors: [
                                          AppTheme.themeConfig.primaryColor.withOpacity(0.1),
                                          AppTheme.themeConfig.primaryColor.withOpacity(0.05),
                                        ],
                                      ),
                                borderRadius: BorderRadius.circular(12),
                              ),
                              child: _buildCodeText(),
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    // 确定按钮
                    SizedBox(
                      width: double.infinity,
                      height: 56,
                      child: Container(
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            begin: Alignment.centerLeft,
                            end: Alignment.centerRight,
                            colors: [
                              AppTheme.themeConfig.primaryColor,
                              AppTheme.themeConfig.primaryColor.withOpacity(0.85),
                            ],
                          ),
                          borderRadius: BorderRadius.circular(16),
                          boxShadow: [
                            BoxShadow(
                              color: AppTheme.themeConfig.primaryColor.withOpacity(0.3),
                              blurRadius: 12,
                              offset: const Offset(0, 4),
                            ),
                          ],
                        ),
                        child: ElevatedButton(
                          onPressed: () {
                            setState(() {
                              clickButtonType = GetSmsCodeClickType.submit;
                            });
                            if (_formKey.currentState!.validate()) {
                              _verifyPhone();
                            }
                          },
                          style: ButtonStyle(
                            shape: MaterialStateProperty.all(
                              RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(16),
                              ),
                            ),
                            backgroundColor: MaterialStateProperty.all(Colors.transparent),
                            elevation: MaterialStateProperty.all(0),
                            shadowColor: MaterialStateProperty.all(Colors.transparent),
                          ),
                          child: const Text(
                            "确定",
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 17,
                              fontWeight: FontWeight.w700,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Text _buildCodeText() {
    if (countdownTime > 0) {
      return Text(
        '${countdownTime}s后重新获取',
        style: TextStyle(
          fontSize: 15,
          color: AppTheme.themeConfig.infoTextColor,
        ),
      );
    } else {
      return Text(
        '获取验证码',
        style: TextStyle(
          fontSize: 15,
          color: AppTheme.themeConfig.primaryColor,
        ),
      );
    }
  }
}
